<template>
  <div class="app-container">
    <div v-show="!detailInfo.visible">
      <!-- 条件栏 -->
      <page-filter
        v-model:query="filterInfo.query"
        :filter-list="filterInfo.list"
      >
        <template v-slot:filter-approve>
          <el-button :disabled="!canApprove"
            v-if="
              $store.state.permission.systemConfig
                .allow_slip_brand_check_approval === 1
            "
            @click="approve()"
            >批准</el-button
          >
        </template>
        <template v-slot:filter-reject>
          <el-button :disabled="!canReject"
            v-if="
              $store.state.permission.systemConfig
                .allow_slip_brand_check_approval === 1
            "
            @click="reject()"
            >驳回</el-button
          >
        </template>
        <template v-slot:filter-refuse>
          <el-button :disabled="!canRefuse"
            v-if="
              $store.state.permission.systemConfig
                .allow_slip_brand_check_approval === 1
            "
            @click="refuse()"
            >拒绝</el-button
          >
        </template>
        <template v-slot:filter-auditTime>
          <el-date-picker
            @change="timeChange"
            v-model="time"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            type="datetimerange"
            range-separator="至"
            :shortcuts="$fn.pickerOptionsFn()"
            align="right"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :default-time="[
              new Date(2000, 1, 1, 0, 0, 0),
              new Date(2000, 1, 1, 23, 59, 59),
            ]"
          ></el-date-picker>
        </template>
      </page-filter>
      <!-- 表格 -->
      <table-container
        :refresh="tableInfo.refresh"
        :init-curpage="tableInfo.initCurpage"
        v-model:data="tableInfo.data"
        :api="tableInfo.api"
        :query="filterInfo.query"
        :field-list="tableInfo.fieldList"
        :handle="tableInfo.handle"
        :row-class-name="tableRowClassName"
        @handleEvent="handleEvent"
      >
        <template v-slot:col-code="scope">
          <span class="slip-edit" @click="openDetail(scope.row)">{{
            scope.row.code
          }}</span>
        </template>
        <template v-slot:col-updateTime="scope">
          <span
            v-if="scope.row.checkStatus === 2 || scope.row.checkStatus === 3"
            >{{ scope.row.updateTime }}</span
          >
          <span v-else>-</span>
        </template>
        <template v-slot:col-updateUserName="scope">
          <span
            v-if="scope.row.checkStatus === 2 || scope.row.checkStatus === 3"
            >{{ scope.row.updateUserName }}</span
          >
          <span v-else>-</span>
        </template>
      </table-container>
    </div>

    <pend-check-brand-detail
      v-if="detailInfo.visible"
      v-model:visible="detailInfo.visible"
      :id="detailInfo.id"
      @returnBack="getList"
    />
  </div>
</template>

<script setup name="pendCheckBrand">
import PageFilter from '@/components/PageFilter/index'
import TableContainer from '@/components/TableContainer/index'
import {
  getBrandCheckPage,
  brandApproved,
  brandRefuse,brandCheckReject
} from '@/api/core'
import { getBusinessKeyById } from '@/api/flowable'
import PendCheckBrandDetail from './detail'
import moment from 'moment'

const { proxy } = getCurrentInstance()
const emit = defineEmits()

const time = ref([])

// 过滤相关配置
const filterInfo = reactive({
  query: {
    sort: 'create_time desc',
    searchType: 'brandCheck',
    updateTimeGreater: '',
    updateTimeLess: '',
  },
  list: [
    {
      type: 'slot',
      value: 'approve',
      abel: '批准',
      show: proxy.$permission('brand:approve'),
    },
    {
      type: 'slot',
      value: 'reject',
      abel: '驳回',
      show: proxy.$permission('brand:reject'),
    },
    {
      type: 'slot',
      value: 'refuse',
      label: '拒绝',
      show: proxy.$permission('brand:refuse'),
    },
    {
      type: 'select-model',
      code: 'slip_platform_check_status',
      clearable: true,
      label: '状态',
      value: 'checkStatus',
      event: search,
    },
    {
      label: '审核日期',
      value: 'auditTime',
      type: 'slot',
      event: search,
    },
    {
      type: 'input',
      value: 'codeLike',
      label: '编码',
      event: search,
    },
    {
      type: 'input',
      value: 'nameLike',
      label: '名称',
      event: search,
    },
    { type: 'button', label: '搜索', event: search },
  ],
})

// 表格相关
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  api: getBrandCheckPage,
  data: [],
  selections: [],
  fieldList: [
    { label: '厂家编码', value: 'code', type: 'slot' },
    { label: '厂家名称', value: 'name' },
    { label: '厂家来源', value: 'supplierName' },
    { label: '状态', value: 'checkStatusValue' },
    { label: '审批意见', value: 'checkOpt' },
    { label: '提交时间', value: 'submitTime' },
    { label: '审核时间', value: 'checkTime' },
    { label: '审核人', value: 'checkUserName' },
    { label: '备注', value: 'remark' },
  ],
  handle: {
    fixed: 'right',
    label: '操作',
    width: '100',
    btList: [
    {
        label: '批准',
        event: approve,
        show: proxy.$permission('brand:approve'),
        ifRender: function (row) {
          return (
            row.checkStatus === 1 &&
            proxy.$store.state.permission.systemConfig
              .allow_slip_brand_check_approval == 1
          )
        },
      },
      {
        label: '驳回',
        event: reject,
        show: proxy.$permission('brand:reject'),
        ifRender: function (row) {
          return (
            row.checkStatus === 1 &&
            proxy.$store.state.permission.systemConfig
              .allow_slip_brand_check_approval == 1
          )
        },
      },
      {
        label: '拒绝',
        event: refuse,
        show: proxy.$permission('brand:refuse'),
        ifRender: function (row) {
          return (
            row.checkStatus === 1 &&
            proxy.$store.state.permission.systemConfig
              .allow_slip_brand_check_approval == 1
          )
        },
      },
    ],
  },
})
const detailInfo = reactive({
  visible: false,
  id: '',
})

const canApprove = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((value) => value.checkStatus !== 1).length === 0
  )
})
const canRefuse = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((value) => value.checkStatus !== 1).length === 0
  )
})
const canReject = computed(() => {
  return (
    tableInfo.selections.length &&
    tableInfo.selections.filter((value) => value.checkStatus !== 1).length === 0
  )
})

const toPage = computed(() => {
  return proxy.$store.state.settings.toPage
})

watch(
  () => filterInfo.query.updateTimeGreater,
  (val) => {
    if (!val) {
      time.value = null
    }
  }
)
watch(
  () => proxy.$router.currentRoute.value.name,
  (to, from) => {
    if (!from) return
    if (
      from.includes('myPendingDetail') ||
      from.includes('myFinishedDetail') ||
      from.includes('myApplyDetail')
    ) {
      getList()
    }
  },
  {
    deep: true,
  }
)

let stopWatch = function () {}
onActivated(() => {
  stopWatch = watch(
    () => toPage.value,
    (val) => {
      if (val) {
        let menus = proxy.$store.state.permission.defaultMenus
        menus.forEach((item) => {
          if (item.children) {
            item.children.forEach((el) => {
              if (el.code === 'pendCheckBrand' && el.url === val.url) {
                detailInfo.visible = false
                if (val.urlType === 1) {
                  getList()
                } else if (val.urlType === 2) {
                  detailInfo.visible = true
                  detailInfo.id = val.businessId
                  sessionStorage.setItem('storeRowId', val.businessId)
                }
                proxy.$store.dispatch('settings/toPage', '')
              }
            })
          }
        })
      }
    },
    {
      deep: true,
      immediate: true,
    }
  )
})
onDeactivated(() => {
  stopWatch()
})
onMounted(() => {
  getList()
})

// 获取列表
function getList() {
  tableInfo.refresh = Math.random()
}
// 搜索
function search() {
  // 重置分页
  tableInfo.initCurpage = Math.random()
  tableInfo.refresh = Math.random()
}
// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case 'tableCheck':
      tableInfo.selections = [...data]
      break
  }
}
function reject(row = undefined) {
  btnFlow(row, 'reject')
}

//确认
function approve(row = undefined) {
  const ids = getIds(row)
  brandApproved({orderIds: ids}).then((resp) => {
    if (resp && resp.success) {
      getList()
    }
  })
}
// 按钮审批原因弹窗
function btnFlow(row, code) {
  let ids = getIds(row)
  let currentBtnFlow = {
    title: '',
    api: null,
  }
  if (code === 'reject') {
    currentBtnFlow.title = '驳回'
    currentBtnFlow.api = brandCheckReject
  } else if (code === 'refuse') {
    currentBtnFlow.title = '拒绝'
    currentBtnFlow.api = brandRefuse
  }
  proxy
    .$prompt('请输入' + currentBtnFlow.title + '理由', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      inputValidator: proxy.$fn.maxString200,
      inputErrorMessage: currentBtnFlow.title + '理由不能超过200字符',
    })
    .then(({ value }) => {
      const data = {
        orderIds: ids,
        checkOpt: value,
      }
      currentBtnFlow.api(data).then((resp) => {
        if (resp && resp.success) {
          search()
        }
      })
    })
}
//拒绝
function refuse(row = undefined) {
  btnFlow(row, 'refuse')
}
function getIds(row) {
  if (row) return [row.id]
  else return tableInfo.selections.map((value) => value.id)
}
function openDetail(row) {
  getBusinessKeyById({
    businessKey: row.id,
    businessType: 'slipBrandCheck',
  }).then((res) => {
    if (res.success) {
      sessionStorage.setItem('storeRowId', row.id)
      if (res.data?.processInstanceId) {
        proxy.$fn.setFlowData(res.data, '', proxy.$route)
      } else {
        detailInfo.id = row.id
        detailInfo.visible = true
      }
    }
  })
}
function tableRowClassName({ row }) {
  let rowId = sessionStorage.getItem('storeRowId')
  if (rowId && row.id === Number(rowId)) {
    return 'check-row'
  }
  return ''
}
function timeChange(val) {
  if (val && val.length) {
    filterInfo.query.updateTimeGreater = val[0]
    filterInfo.query.updateTimeLess = val[1]
  } else {
    filterInfo.query.updateTimeGreater = ''
    filterInfo.query.updateTimeLess = ''
  }
}
</script>

<style scoped></style>
